package xyz.syyrjx.blog.controller.admin;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import xyz.syyrjx.blog._enum.State;
import xyz.syyrjx.blog.entity.Blog;
import xyz.syyrjx.blog.entity.Result;
import xyz.syyrjx.blog.entity.Types;
import xyz.syyrjx.blog.service.BlogService;
import xyz.syyrjx.blog.service.TypeService;
import xyz.syyrjx.blog.util.PageUtil;

import javax.annotation.Resource;
import java.util.List;


@Controller
@RequestMapping("/admin")
public class TypeController {
    @Resource
    private TypeService typeService;
    @Resource
    private BlogService blogService;


    @RequestMapping("/types")
    public ModelAndView types(Integer page,Integer next){
        List<Types> typesList = null;
        int count = typeService.countTypes();
        page = PageUtil.pageGet(count,page,next,10);
        typesList = typeService.queryTypesInPage(page);
        ModelAndView mv = new ModelAndView();
        mv.addObject("typesList",typesList);
        mv.addObject("page",page);
        mv.setViewName("admin/types");
        return mv;
    }

    @RequestMapping("/type_add")
    public String typeAdd(){
        return "admin/type_add";
    }

    @GetMapping("/deleteType")
    @ResponseBody
    public Result deleteType(Long id){
        Blog blogTemplate = new Blog();
        blogTemplate.setState(State.NORMAL_STATE.getCode());
        blogTemplate.setType(id);
        if(blogService.queryBlogs(blogTemplate,null).size() == 0){
            Types type = new Types(id,null);
            if(typeService.deleteType(type)){
                return Result.success(typeService.queryAllTypes());
            }
        }
        return Result.fail("本分类下还有文章，无法删除");
    }

    @RequestMapping("addAType")
    @ResponseBody
    public String addAType(String name){
        String res = "添加失败";
        if(typeService.addType(name)){
            res = "添加成功";
        }
        return res;
    }
}
